<?php

namespace SunAdmin\Common;

use think\facade\Cache;
use think\facade\Config;

class TokenHelper
{
    protected static function getSecret(): string
    {
        return config('app.token_secret', "sunadmin-sunjinglong@lingyier.com");
    }

    protected static function getTtl(): int
    {
        return config('app.token_ttl', 3600);
    }

    /**
     * 生成 token
     * $cacheTag 缓存标签,为了区分admin还是client
     */
    public static function generate(int $uid, string $cacheTag): string
    {
        if (empty($cacheTag)) {
            throw new \Exception("token缓存标签参数不能为空");
        }
        $cacheTag .= "_token";
        $token = bin2hex(random_bytes(32));
        Cache::tag($cacheTag)->set($token, $uid, self::getTtl());
        return $token;
    }

    /**
     * 验证 token
     */
    public static function verify(string $token): array|false
    {
        $uid = Cache::get($token);
        if (!$uid) return false;
        return ['uid' => (int)$uid];
    }

    /**
     * 删除某个用户所有登录token
     */
    public static function delete($uid, $cacheTag)
    {
        if (empty($cacheTag)) {
            throw new \Exception("token缓存标签参数不能为空");
        }
        $cacheTag .= "_token";
        $tokenList = Cache::getTagItems($cacheTag);
        foreach ($tokenList as $token) {
            if (Cache::get($token) == $uid) {
                Cache::delete($token);
            }
        }
        return true;
    }
}
